package boun.center;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class BounNewsFetcher {
	
	private static final int NEWS_LIMIT = 5;
	private static final String SOURCE_URL = "http://www.boun.edu.tr/en-US/Content/About_BU/Corporate_Communication/News.aspx";
	
	public static ArrayList<BounNews> fetchBounNews() throws IOException, ParseException, IllegalStateException, JSONException {
		String webContent = WebDownloader.fetchWebContent(SOURCE_URL);
		return parseBounNews(webContent);
	}

	private static ArrayList<BounNews> parseBounNews(String content) throws IOException, ParseException {
		ArrayList<BounNews> res = new ArrayList<BounNews>();
		Pattern innerTablePattern = Pattern.compile("<div id=\"ctl00_MainContent_Module653_ListPanel\" class=\"list\">\\s*?<ul>\\s*?(.*?)\\s*?</ul>");

		Pattern rowPattern = Pattern.compile("class=\"date\">\\s*?(.*?)\\s*?</span>.*?(LoadModule.*?true).*?void\\(0\\)\">(.*?)</a>");
		Matcher matcher = innerTablePattern.matcher(content);
		if (matcher.find()) {
			String innerContent = matcher.group(1).trim();
			matcher = rowPattern.matcher(innerContent);
			int i = 0;
			while (matcher.find() && i < NEWS_LIMIT) {
				Calendar cal = Calendar.getInstance();
				SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy", Locale.US);
				String dateString = matcher.group(1).trim();
				cal.setTime(sdf.parse(dateString));
	
				String url = SOURCE_URL + "?" + matcher.group(2).trim();
				url = url.replaceAll("&amp;", "&");
				String description = Util.sanifyString(getNewsContent(url));
				String subject = Util.sanifyString(matcher.group(3));
				
				res.add(new BounNews(subject, description, url, cal));
				++i;
			}
		}
		return res;
	}
	
	private static String getNewsContent(String url) throws IOException {
		String content = WebDownloader.fetchWebContent(url);
		Pattern textPattern = Pattern.compile("class=\"detail\">\\s*?(.*?)\\s*?</div>");
		Matcher matcher = textPattern.matcher(content);
		if (matcher.find()) {
			return matcher.group(1);
		} else {
			return null;
		}
	}
}
